<script setup>
import { ref, onMounted } from 'vue'
import { useGoodsService } from '@/api/requsets/index.js'
import { useRoute } from 'vue-router'
import GoodsItem from '@/components/GoodsItem.vue'

//当前路由数据
const route = useRoute()

// 选中常亮 标记变量
const actives = ref([false, false, false])

// 商品搜索关键词  路由query传参
const goodsName = ref('')

// 商品分类id  路由路径传参
const categoryId = ref('')

// 商品价格排序 控制变量 true-价格从低到高 false-价格从高到低
const sortPriceFlag = ref(true)

// 搜索回来的商品列表
const goodsSearchList = ref([])

// 处理排序的回调
const handlerSort = async (index = 0, sortType, sortPrice = '0') => {
  // 处理高亮
  actives.value = actives.value.map((item) => {
    item = false
    return item
  })
  actives.value[index] = true
  // 获取搜索商品数据
  const {
    data: {
      list: { data }
    }
  } = await useGoodsService({
    sortType, // all-按综合搜索(默认)，sales-按销量搜索，price-按价格搜索
    sortPrice, //价格排序变量 0-价格从低到高 1-价格从高到低
    categoryId: categoryId.value, //分类id  可选 示例值:0
    goodsName: goodsName.value, // 商品名称
    page: '1' // 页码 默认 1
  })
  goodsSearchList.value = data
}
// 专门处理价格排序的回调
const handlerPriceSort = (index, sortType) => {
  sortPriceFlag.value = !sortPriceFlag.value
  handlerSort(index, sortType, sortPriceFlag.value ? '0' : '1')
}

onMounted(async () => {
  goodsName.value = route.query?.goodsName
  categoryId.value = route.params?.categoryId
  await handlerSort()
})
</script>

<template>
  <div class="search-list">
    <van-nav-bar title="商品列表" left-arrow @click-left="$router.go(-1)" />
    <van-search
      v-model="goodsName"
      autocomplete="off"
      @search="handlerSort"
      shape="round"
      show-action
      placeholder="搜索关键词"
    >
      <template #action>
        <div @click="handlerSort">搜索</div>
      </template>
    </van-search>
    <ul class="sort-list">
      <li
        :class="{ 'sort-item': true, active: actives[0] }"
        @click="handlerSort(0, 'all')"
      >
        综合
      </li>
      <li
        :class="{ 'sort-item': true, active: actives[1] }"
        @click="handlerSort(1, 'sales')"
      >
        销量
      </li>
      <li
        :class="{ 'sort-item': true, active: actives[2] }"
        @click="handlerPriceSort(2, 'price')"
      >
        价格
        <van-icon v-if="sortPriceFlag" name="arrow-down" />
        <van-icon v-else name="arrow-up" />
      </li>
    </ul>
    <GoodsItem
      v-for="item in goodsSearchList"
      :item="item"
      :key="item.goods_id"
      @click="$router.push(`/goodsDetail/${item.goods_id}`)"
      mode="normal"
    ></GoodsItem>
  </div>
</template>

<style lang="less">
.search-list {
  //padding: 20px;
  .van-badge__wrapper.van-icon.van-icon-apps-o {
    font-size: 24px;
    vertical-align: sub;
  }
  .sort-list {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin: auto;
    padding: 10px 20px;
    .sort-item {
      font-size: 16px;

      &.active {
        font-weight: bold;
        color: #c21401;
      }
    }
  }
}
</style>
